package flag

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/ctype"
	"blog_go/utils"
	"fmt"
	"github.com/sirupsen/logrus"
)

func CreateUser(permissions string) {
	// 用户名 昵称 密码 确认密码 邮箱
	var (
		username   string
		nickname   string
		password   string
		rePassword string
		email      string
	)
	fmt.Printf("请输入用户名:")
	// Scan和Scanln  Scanln可以不输入直接回车
	fmt.Scan(&username)
	fmt.Printf("请输入用户昵称:")
	fmt.Scan(&nickname)
	fmt.Printf("请输入密码:")
	fmt.Scan(&password)
	fmt.Printf("请确认密码:")
	fmt.Scan(&rePassword)
	fmt.Printf("请输入邮箱:")
	fmt.Scan(&email)
	//fmt.Scanln(&email)
	// 判断用户名是否存在
	var userModel models.UserModel
	err := global.DB.Take(&userModel, "user_name=?", username).Error
	// 没查询到数据会有错误
	if err == nil {
		// 存在
		logrus.Error("用户名已存在")
		return
	}
	if password != rePassword {
		logrus.Error("两次密码不一致")
		return
	}
	// 对密码进行hash
	pwdHash := utils.HashPwd(password)
	// 新建用户
	role := ctype.PermissionUser
	if permissions == "admin" {
		role = ctype.PermissionAdmin
	}
	global.DB.Create(&models.UserModel{
		NickName:   nickname,
		UserName:   username,
		Password:   pwdHash,
		Avatar:     "/uploads/default_avatar.jpg",
		Email:      email,
		Tel:        "110",
		Addr:       "内网地址",
		Token:      "0000",
		IP:         "127.0.0.1",
		Role:       role,
		SignStatus: ctype.SignEmail,
	})
	logrus.Info("新建用户成功")
}
